<?php
/****
//ini_set("session.save_handler", "memcache");
//ini_set("session.save_path", "tcp://127.0.0.1:11211"); 
//使用多个 memcached server 时用逗号","隔开，并且和 Memcache::addServer() 文档中说明的一样，
//可以带额外的参数"persistent"、"weight"、"timeout"、"retry_interval" 等等，
//类似这样的："tcp://host1:port1?persistent=1&weight=2,tcp://host2:port2" 。
class Session_Memcached1{
    public function __construct() {
        //测试不成功
        ini_set("session.save_handler", "memcached");
        ini_set("session.save_path", "tcp://127.0.0.1:11211"); 
    }
}

***/

class Session_Memcached2 {

    private static $life_time = 3600;
    /**
     *
     * @var QCache_Memcached
     */
    static $backend = null;
    
    public function __construct() {
        $app_config = Q::ini("/");
        $backend = "QCache_Memcached";
        $settings = isset($app_config['runtime_session_setting'][$backend]) ? $app_config['runtime_session_setting'][$backend] : $app_config['runtime_cache_backend_config'];
//        if(is_null(self::$backend)){
            self::$backend = new $backend($settings);
//        }
            $settings['compressed']=false;
        self::$life_time = isset($settings['life_time'])?$settings['life_time']:ini_get('session.gc_maxlifetime');
        ini_set('session.use_trans_sid', 0);
        ini_set('session.gc_maxlifetime', self::$life_time);
        ini_set('session.use_cookies', 1);
        ini_set('session.cookie_path', '/');
        session_module_name('user');
        session_set_save_handler(
            array($this, 'open'), array($this, 'close'), array($this, 'read'), array($this, 'write'), array($this, 'destroy'), array($this, 'gc')
        );
    }
    
    public  function open() {
        return true;
    }

    public  function read($id) {
        return self::$backend->get("sessions/{$id}");
    }

    public  function write($id, $data) {
        return self::$backend->set("sessions/{$id}", $data, self::$life_time);
    }

    public  function destroy($id) {
        return self::$backend->delete("sessions/{$id}");
    }

    public  function gc() {
        return true;
    }

    public  function close() {
        return true;
    }

    public function __destruct() {
//        self::$backend = null;
        session_write_close();
    }

}

class Session_Memcached {
//设定 SESSION 有效时间，单位是 秒
    const SESS_LIFTTIME=3600;
    static $mSessSavePath;
    static $mSessName;
    static $backend = null;
    public $domain;

    public function __construct() {
        $this->key_prefix = "sess_";
        $backend = "QCache_Memcached";
        $app_config = Q::ini("/");
        $settings = isset($app_config['runtime_session_setting'][$backend]) ? $app_config['runtime_session_setting'][$backend] : $app_config['runtime_cache_backend_config'];
        if(is_null(self::$backend)){
            self::$backend = new $backend($settings);
        }
        $this->_init();
        return TRUE;
    }

    public function sessOpen($pSavePath = '', $pSessName = '') {
        self::$mSessSavePath = $pSavePath;
        self::$mSessName = $pSessName;

        return TRUE;
    }

    public function sessClose() {
        return TRUE;
    }

    public function sessRead($sess_id = '') {
        $sess_data = self::$backend->get($this->key_prefix . $sess_id);
        //先读数据，如果没有，就初始化一个
        if (!empty($sess_data)) {
            return $sess_data;
        } else {
            $this->sessWrite($sess_id, '');
        }
        return true;
    }

    public function sessWrite($sess_id, $sess_data = '') {
        $ret = self::$backend->set($this->key_prefix . $sess_id, $sess_data, array('life_time' => self::SESS_LIFTTIME, 'compressed' => true));
        if (TRUE != $ret) {
            die("Fatal Error: SessionID $sess_id Save data failed!");
            return FALSE;
        }
        return TRUE;
    }

    public function sessDestroy($sess_id = '') {
        $ret = self::$backend->remove($sess_id);
        return FALSE;
    }

    public function sessGc() {
        //无需额外回收,memcache有自己的过期回收机制
        return TRUE;
    }

    public function _init() {
        //不使用 GET/POST 变量方式
        ini_set('session.use_trans_sid', 0);
        //设置垃圾回收最大生存时间
        ini_set('session.gc_maxlifetime', self::SESS_LIFTTIME);
        //使用 COOKIE 保存 SESSION ID 的方式
        ini_set('session.use_cookies', 1);
        ini_set('session.cookie_path', '/');
        //多主机共享保存 SESSION ID 的 COOKIE
        ini_set('session.cookie_domain', $this->domain);
        //将 session.save_handler 设置为 user，而不是默认的 files
        session_module_name('user');
        //定义 SESSION 各项操作所对应的方法名：
        session_set_save_handler(
                array($this, 'sessOpen'), array($this, 'sessClose'), array($this, 'sessRead'), array($this, 'sessWrite'), array($this, 'sessDestroy'), array($this, 'sessGc')
        );
        return TRUE;
    }

}

//end class

//$memcached_session = new Session_Memached();
?>
